<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2023/6/15
 * Time: 10:32
 */
namespace app\index\controller;

use app\index\service\DyOpenService;
use app\index\service\KsOpenService;
use app\index\service\PayService;
use app\middleware\Check;
use think\Exception;
use think\facade\Db;

class Order{

    protected $middleware = [
        Check::class => ['except' 	=> ['getProduct','getOpenCity'] ]
    ];


    /**
     * 已开通城市列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOpenCity(){
        $list = Db::name('region')
            ->where('is_open',1)
            ->select()->toArray();

        return success('已开通城市列表',$list);
    }

    /**
     * 获取购买的套餐
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getProduct(){
        validateParam('city','city');
        $city = input('city');
        //首先判断该城市下面有地方题库吗
        $chapter = Db::name('chapter')
            ->where('city_',$city)
            ->find();
        //获取题库的价格
        $products = Db::name('system_content_setting')
            ->where('key','in',['product1','product2','product3','product4','old_product1','old_product2','old_product3','old_product4'])
            ->select()->toArray();
        $temp = [];
        foreach ($products as $k=>$v){
            $temp[$v['key']] = $v['value'];
        }
        //说明有题库
        if(!empty($chapter)) {
            //首先判断该城市下面有技巧题库吗
            $skill_chapter = Db::name('skill_chapter')
                ->where('city_', $city)
                ->find();
            if (!empty($skill_chapter)) {
                //说明既有地方题库也有技巧题库
                $list[] = [
                    'type'=>'1',
                    'name'=>'技巧版',
                    'sub_name'=>"【全国+{$city}】所有题库和技巧",
                    'price'=>$temp['product1'],//99.9
                    'old_price'=>$temp['old_product1'],//129.9
                    'unlock_info'=>[
                        ['city'=>'0','is_unlock_question'=>1,'is_unlock_skill'=>1],
                        ['city'=>$city,'is_unlock_question'=>1,'is_unlock_skill'=>1]
                    ]
                ];
                $list[] = [
                    'type'=>'2',
                    'name'=>'标准版',
                    'sub_name'=>"【仅题库无技巧】全国题库+{$city}区域题库",
                    'price'=>$temp['product2'],//29.9
                    'old_price'=>$temp['old_product2'],//39.9
                    'unlock_info'=>[
                        ['city'=>'0','is_unlock_question'=>1,'is_unlock_skill'=>0],
                        ['city'=>$city,'is_unlock_question'=>1,'is_unlock_skill'=>0]
                    ]
                ];
            } else {
                //只有地方题库，没有地方技巧题库
                $list[] = [
                    'type'=>'1',
                    'name'=>'技巧版',
                    'sub_name'=>"【仅全国技巧】全国题库技巧+{$city}区域题库",
                    'price'=>$temp['product3'],//59.9
                    'old_price'=>$temp['old_product3'],//79.9
                    'unlock_info'=>[
                        ['city'=>'0','is_unlock_question'=>1,'is_unlock_skill'=>1],
                        ['city'=>$city,'is_unlock_question'=>1,'is_unlock_skill'=>0]
                    ]
                ];
                $list[] = [
                    'type'=>'2',
                    'name'=>'标准版',
                    'sub_name'=>"【仅题库无技巧】全国题库+{$city}区域题库",
                    'price'=>$temp['product2'],//29.9
                    'old_price'=>$temp['old_product2'],//39.9
                    'unlock_info'=>[
                        ['city'=>'0','is_unlock_question'=>1,'is_unlock_skill'=>0],
                        ['city'=>$city,'is_unlock_question'=>1,'is_unlock_skill'=>0]
                    ]
                ];
            }
        }else{
            //没有地方题库，只有全国题库和技巧题库
            $list[] = [
                'type'=>'1',
                'name'=>'技巧版',
                'sub_name'=>"【仅全国技巧】全国题库+全国技巧",
                'price'=>$temp['product4'],//29.9
                'old_price'=>$temp['old_product4'],//59.9
                'unlock_info'=>[
                    ['city'=>'0','is_unlock_question'=>1,'is_unlock_skill'=>1]
                ]
            ];
        }
        return success('购买的套餐数据',$list);
    }


    /**
     * 套餐下单
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function placeDyOrder(){
        validateParam('car_id,address,test_drive_date,mobile,name,id_card_font,id_card_back,license','car_id,address,test_drive_date,mobile,name,id_card_font,id_card_back,license');
        $param = input();
        $data['user_id'] = uid();
        $data['order_no'] = snowflake();
        $carInfo = Db::name('cars')->where(['id' => input('car_id'), 'status' => 1])->find();
        if (empty($carInfo)) {
            return error('试驾车辆已下架');
        }
//        if (strtotime($param['test_drive_date']) < time()) {
//            return error('试驾车辆已下架');
//        }
        $carName = $carInfo['car_name'] . $carInfo['car_vehicle_code'];
        $data['order_name'] = $carName . '车辆试驾';
        $data['car_id'] = $param['car_id'];
        $data['address'] = $param['address'];
        $data['mobile'] = $param['mobile'];
        $data['name'] = $param['name'];
        $data['test_drive_date'] = $param['test_drive_date'];
        $data['id_card_font'] = $param['id_card_font'];
        $data['id_card_back'] = $param['id_card_back'];
        $data['license'] = $param['license'];
        $data['pay_money'] = $carInfo['test_drive_fee'];
        $data['pay_type'] = 'dy';
        $data['create_at'] = currentTime();//订单创建时间
        Db::startTrans();
        try {
            $order_id = Db::name('pay_order')->insertGetId($data);
            $dy = new DyOpenService();

            //获取用户的快手openid
//            $user = Db::name('user')->where('id', uid())->find();
//            $result = $dy->createNewOrder($user['dy_openid'],$data['order_no'],$order_id,$data['pay_money'],config('system.dyDeveloper.notify_url'));
//            $result = [];
            $result = $dy->createOrder($data['order_no'], $data['pay_money'], $data['order_name'], $data['order_name'], config('system.dyDeveloper.notify_url'));
            Db::commit();
            return success('下单成功', $result);
        }catch (Exception $e){
            Db::rollback();
            return error($e->getMessage());
        }
    }

    /**
     * 获取支付信息
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getPayInfo(){
        validateParam('order_id','order_id');
        $where['user_id'] = uid();
        $where['id'] = input('order_id');
        $orderInfo = Db::name('pay_order')->where($where)->find();
        if (empty($orderInfo)) {
            return error('订单未找到');
        }
        if ($orderInfo['status'] != '0') {
            return error('订单状态异常');
        }

        $dy = new DyOpenService();
        $result = $dy->createOrder($orderInfo['order_no'], $orderInfo['pay_money'], $orderInfo['order_name'], $orderInfo['order_name'], config('system.dyDeveloper.notify_url'));
        return success('获取成功', $result);
    }


    /**
     * 套餐下单(微信)
     * @return \think\response\Json
     * @throws \WeChat\Exceptions\InvalidResponseException
     * @throws \WeChat\Exceptions\LocalCacheException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function placeWxOrder(){
        validateParam('type,city','type,city');
        $param = input();
        $data['user_id'] = uid();
        $data['order_no'] = snowflake();
        if($param['type'] == '1') {
            $data['order_name'] = "{$param['city']}VIP版套餐";
        }else{
            $data['order_name'] = "{$param['city']}标准版套餐";
        }
        $city = $param['city'];
        //首先判断该城市下面有地方题库吗
        $chapter = Db::name('chapter')
            ->where('city_',$city)
            ->find();
        //获取题库的价格
        $products = Db::name('system_content_setting')
            ->where('key','in',['product1','product2','product3','product4'])
            ->select()->toArray();
        $temp = [];
        foreach ($products as $k=>$v){
            $temp[$v['key']] = $v['value'];
        }
        $list = [];
        //说明有题库
        if(!empty($chapter)) {
            //首先判断该城市下面有技巧题库吗
            $skill_chapter = Db::name('skill_chapter')
                ->where('city_', $city)
                ->find();
            if (!empty($skill_chapter)) {
                //说明既有地方题库也有技巧题库
                $list[] = [
                    'type'=>'1',
                    'name'=>'VIP版',
                    'sub_name'=>"【全国+{$city}】所有题库和懒人技巧练习",
                    'price'=>$temp['product1'],//99.9
                    'old_price'=>129.9,
                    'unlock_info'=>[
                        ['city'=>'0','is_unlock_question'=>1,'is_unlock_skill'=>1],
                        ['city'=>$city,'is_unlock_question'=>1,'is_unlock_skill'=>1]
                    ]
                ];
                $list[] = [
                    'type'=>'2',
                    'name'=>'标准版',
                    'sub_name'=>"【仅题库无技巧】全国题库+{$city}区域题库练习",
                    'price'=>$temp['product2'],//29.9
                    'old_price'=>39.9,
                    'unlock_info'=>[
                        ['city'=>'0','is_unlock_question'=>1,'is_unlock_skill'=>0],
                        ['city'=>$city,'is_unlock_question'=>1,'is_unlock_skill'=>0]
                    ]
                ];
            } else {
                //只有地方题库，没有地方技巧题库
                $list[] = [
                    'type'=>'1',
                    'name'=>'VIP版',
                    'sub_name'=>"【仅全国技巧】全国题库懒人技巧练习+{$city}区域题库",
                    'price'=>$temp['product3'],//59.9
                    'old_price'=>79.9,
                    'unlock_info'=>[
                        ['city'=>'0','is_unlock_question'=>1,'is_unlock_skill'=>1],
                        ['city'=>$city,'is_unlock_question'=>1,'is_unlock_skill'=>0]
                    ]
                ];
                $list[] = [
                    'type'=>'2',
                    'name'=>'标准版',
                    'sub_name'=>"【仅题库无技巧】全国题库+{$city}区域题库练习",
                    'price'=>$temp['product2'],//29.9
                    'old_price'=>39.9,
                    'unlock_info'=>[
                        ['city'=>'0','is_unlock_question'=>1,'is_unlock_skill'=>0],
                        ['city'=>$city,'is_unlock_question'=>1,'is_unlock_skill'=>0]
                    ]
                ];
            }
        }else{
            //没有地方题库，只有全国题库和技巧题库
            $list[] = [
                'type'=>'1',
                'name'=>'VIP版',
                'sub_name'=>"【仅全国技巧】全国题库+全国技巧",
                'price'=>$temp['product4'],//29.9
                'old_price'=>59.9,
                'unlock_info'=>[
                    ['city'=>'0','is_unlock_question'=>1,'is_unlock_skill'=>1]
                ]
            ];
        }
        if($param['type'] == '1'){
            //选择的vip套餐
            if(!isset($list[0])){
                return error('下单错误');
            }
            $data['pay_money'] = $list[0]['price'];
            $data['unlock_info'] = json_encode($list[0]['unlock_info']);
        }else{
            //选择的标准套餐
            if(!isset($list[1])){
                return error('下单错误');
            }
            $data['pay_money'] = $list[1]['price'];
            $data['unlock_info'] = json_encode($list[1]['unlock_info']);
        }
        $data['city'] = $city;
        $data['type'] = $param['type'];
        $data['pay_type'] = 'dy';
        $data['create_at'] = currentTime();//订单创建时间
        Db::name('pay_order')->insert($data);

        //获取用户的openid
        $openid = Db::name('user')
            ->where('id',uid())
            ->value('wx_openid');
        $wx = new PayService();
        $result = $wx->weCreateOrder($data['order_name'],$data['order_no'],$data['pay_money'],config('system.weChatDeveloper.notify_url'),$openid);
        return success('下单',$result);
    }


    /**
     * 套餐下单(快手)
     * @return \think\response\Json
     * @throws \Exception
     */
    public function placeKsOrder(){
        validateParam('type,city','type,city');
        $param = input();
        $data['user_id'] = uid();
        $data['order_no'] = snowflake();
        if($param['type'] == '1') {
            $data['order_name'] = "{$param['city']}VIP版套餐";
        }else{
            $data['order_name'] = "{$param['city']}标准版套餐";
        }
        $city = $param['city'];
        Db::startTrans();
        try {
            //首先判断该城市下面有地方题库吗
            $chapter = Db::name('chapter')
                ->where('city_', $city)
                ->find();
            //获取题库的价格
            $products = Db::name('system_content_setting')
                ->where('key', 'in', ['product1', 'product2', 'product3', 'product4'])
                ->select()->toArray();
            $temp = [];
            foreach ($products as $k => $v) {
                $temp[$v['key']] = $v['value'];
            }
            $list = [];
            //说明有题库
            if (!empty($chapter)) {
                //首先判断该城市下面有技巧题库吗
                $skill_chapter = Db::name('skill_chapter')
                    ->where('city_', $city)
                    ->find();
                if (!empty($skill_chapter)) {
                    //说明既有地方题库也有技巧题库
                    $list[] = [
                        'type' => '1',
                        'name' => 'VIP版',
                        'sub_name' => "【全国+{$city}】所有题库和懒人技巧练习",
                        'price' => $temp['product1'],//99.9
                        'old_price' => 129.9,
                        'unlock_info' => [
                            ['city' => '0', 'is_unlock_question' => 1, 'is_unlock_skill' => 1],
                            ['city' => $city, 'is_unlock_question' => 1, 'is_unlock_skill' => 1]
                        ]
                    ];
                    $list[] = [
                        'type' => '2',
                        'name' => '标准版',
                        'sub_name' => "【仅题库无技巧】全国题库+{$city}区域题库",
                        'price' => $temp['product2'],//29.9
                        'old_price' => 39.9,
                        'unlock_info' => [
                            ['city' => '0', 'is_unlock_question' => 1, 'is_unlock_skill' => 0],
                            ['city' => $city, 'is_unlock_question' => 1, 'is_unlock_skill' => 0]
                        ]
                    ];
                } else {
                    //只有地方题库，没有地方技巧题库
                    $list[] = [
                        'type' => '1',
                        'name' => 'VIP版',
                        'sub_name' => "【仅全国技巧】全国题库懒人技巧练习+{$city}区域题库",
                        'price' => $temp['product3'],//59.9
                        'old_price' => 79.9,
                        'unlock_info' => [
                            ['city' => '0', 'is_unlock_question' => 1, 'is_unlock_skill' => 1],
                            ['city' => $city, 'is_unlock_question' => 1, 'is_unlock_skill' => 0]
                        ]
                    ];
                    $list[] = [
                        'type' => '2',
                        'name' => '标准版',
                        'sub_name' => "【仅题库无技巧】全国题库+{$city}区域题库",
                        'price' => $temp['product2'],//29.9
                        'old_price' => 39.9,
                        'unlock_info' => [
                            ['city' => '0', 'is_unlock_question' => 1, 'is_unlock_skill' => 0],
                            ['city' => $city, 'is_unlock_question' => 1, 'is_unlock_skill' => 0]
                        ]
                    ];
                }
            } else {
                //没有地方题库，只有全国题库和技巧题库
                $list[] = [
                    'type' => '1',
                    'name' => 'VIP版',
                    'sub_name' => "【仅全国技巧】全国题库+全国技巧",
                    'price' => $temp['product4'],//29.9
                    'old_price' => 59.9,
                    'unlock_info' => [
                        ['city' => '0', 'is_unlock_question' => 1, 'is_unlock_skill' => 1]
                    ]
                ];
            }
            if ($param['type'] == '1') {
                //选择的vip套餐
                if (!isset($list[0])) {
                    return error('下单错误');
                }
                $data['pay_money'] = $list[0]['price'];
                $data['unlock_info'] = json_encode($list[0]['unlock_info']);
            } else {
                //选择的标准套餐
                if (!isset($list[1])) {
                    return error('下单错误');
                }
                $data['pay_money'] = $list[1]['price'];
                $data['unlock_info'] = json_encode($list[1]['unlock_info']);
            }
            $data['city'] = $city;
            $data['type'] = $param['type'];
            $data['pay_type'] = 'ks';
            $data['create_at'] = currentTime();//订单创建时间
            Db::name('pay_order')->insert($data);

            //获取用户的快手openid
            $openid = Db::name('user')
                ->where('id', uid())
                ->value('ks_openid');
            $ks = new KsOpenService();
            $result = $ks->createOrder((string)$data['order_no'], $openid, $data['pay_money'], $data['order_name'], $data['order_name'], config('system.ksDeveloper.notify_url'));
            // 提交事务
            Db::commit();
            return success('快手下单', $result);
        }catch (Exception $e){
            Db::rollback();
            return error($e->getMessage());
        }
    }
}